<?php

namespace app\common\model;

use app\common\controller\Weixin;
use think\Db;
use think\Exception;
use think\Model;

class BatchOrder extends Model
{
    // 表名
    protected $name = 'batch_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'pay_time_text',
	    'pay_type_text'
    ];
    
    
    const STATUS_W = 0;
    const STATUS_Y = 1;
    
    public static $_status = [
        self::STATUS_Y => '支付成功',
	    self::STATUS_W => '待支付'
    ];

    
    public function getStatusList()
    {
        return self::$_status;
    }     

    const TYPE_ALI = 1;
    const TYPE_WEIXIN = 2;
    
    public static $_types = [
        self::TYPE_ALI => '支付宝',
	    self::TYPE_WEIXIN => '微信',
    ];
    

    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	
	public function getPayTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['pay_type'];
		$list = self::$_types;
		return isset($list[$value]) ? $list[$value] : '';
	}
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
    
    
    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 创建批量支付记录
	 * @param $userId 用户ID
	 * @param $ids 批量支付的订单ID如1,2,3
	 * @param $amount 支付总金额
	 * @return bool|string
	 */
    public function createRecord($userId, $ids, $amount){
    	$no = time().rand(111111, 999999);
	    $batchData = [
		    'no' => $no,
		    'order_ids' => $ids,
		    'user_id' => $userId,
		    'amount' => $amount,
	    ];
	    
	    $res = $this->isUpdate(false)->save($batchData);
	    if($res) {
	    	return $no;
	    } else {
	    	return false;
	    }
    }
	
	/**
	 * 更改批量记录状态及订单状态
	 * @param $no 记录单号
	 * @param $trade_no 交易流水号
	 * @param $payType 支付方式
	 * @param $amount 支付金额
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
    public function paySuccess($no, $trade_no, $payType, $amount) {
    	$row = $this->where(['no' => $no])->find();
    	if(!$row) {
    		$this->error = '记录不存在';
    		return false;
    	}
    	
    	if($row['amount'] != $amount) {
    		$this->error = '支付金额不正确';
    		return false;
	    }
     
    	if($row['status'] != self::STATUS_W) {
    		$this->error = '该记录已经支付';
	    }
	    
	    $this->startTrans();
    	try{
    	    //更改批量记录状态
		    $row['status'] = self::STATUS_Y;
		    $row['trade_no'] = $trade_no;
		    $row['pay_type'] = $payType;
		    $row['pay_time'] = time();
		    $res = $row->save();
		    if(!$res) {
		    	throw new Exception('更改记录状态出错');
		    }
		    
		    $orderModel = new Order();
		    //查找对应的订单
		    $ids = explode(',', $row['order_ids']);
		    $where = [
			    'order_status' => $orderModel::STATUS_WAIT_PAYMENT,
			    'id' => ['in', $ids]
		    ];
		    $orders = Db::name('order')
			    ->where($where)
			    ->select();
		    
		    if($orders) {
		        foreach($orders as $order) {
		        	$pay_type = $payType == self::TYPE_ALI ? Payment::PAY_TYPE_ALI : Payment::PAY_TYPE_WEIXIN;
					$orderRes = $orderModel->paySuccess($order, $pay_type, $trade_no);
					if(!$orderRes) {
						throw new Exception($orderModel->getError());
					}
		        }
		    }
		    
		    $this->commit();
		
		    if($row['prepay_id']){
		    	$this->sendTemplate($row, $orders);
		    }
		   
		    
	    } catch (Exception $e) {
    		$this->error = $e->getMessage();
    		$this->rollback();
    		return false;
	    }
    
	    return true;
    }
    
    
    public function sendTemplate($row, $orders){
	    //发送模板通知
	    $obj = new Weixin();
	    foreach($orders as $order) {
		    $goods = Db::name('orderGoods')
			    ->where(['order_id' => $order['id']])
			    ->column('goods_name', 'id');
		
		
		    $goodsName = implode(',', $goods);
		    $data = [
			    'keyword1' => ['value' => $order['order_no']],
			    'keyword2' => ['value' => $order['order_amount']],
			    'keyword3' => ['value' => date('Y-m-d H:i:s', $order['create_time'])],
			    'keyword4' => ['value' => $goodsName],
		    ];
		
		    $weixinInfo = Db::name('weixinInfo')->where(['user_id' => $row['user_id']])->find();
		    $res = $obj->sendTemplate($weixinInfo['openid'], '8wpcSa7Iu7Nv1YITc2fE0Yqdye_aIFCgekOkcLRISb0',
			    $row['prepay_id'], $data, 'pages/order/detail/index?order_id=' . $order['id']);
	    }
    }
}
